package com.oscchina.xushao.ui;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.oscchina.xushao.MainActivity;
import com.oscchina.xushao.R;
import com.oscchina.xushao.adapter.ListViewBlogAdapter;
import com.oscchina.xushao.app.AppContext;
import com.oscchina.xushao.app.AppException;
import com.oscchina.xushao.bean.Blog;
import com.oscchina.xushao.bean.BlogList;
import com.oscchina.xushao.common.UIHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * 资讯-资讯的子类，包括最新博客、推荐阅读
 *
 * @author XuShaoJie
 * @version 2013-07-05
 */
public class InfoBlogFragment extends Fragment {

    // private PullToRefreshListView mPullRefreshListView;
    private ListView mPullRefreshListView;

    private ListViewBlogAdapter mNewsAdapter;
    private List<Blog> lvNewsDataList = new ArrayList<Blog>();
    private int lvSumData;// 加载的总数目
    private static int BLOG_FLAG = 0;

    private AppContext appContext;// 全局Context

    /**
     * 返回InfoBlogFragment实例
     *
     * @param type 加载数据的类型
     * @return FavoriteFragment实例
     */
    public static InfoBlogFragment newInstance(String type) {
        InfoBlogFragment ff = new InfoBlogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        ff.setArguments(bundle);
        BLOG_FLAG = 1;

        return ff;
    }

    /**
     * 返回查看用户信息的时候，加载的博客列表
     *
     * @param hisUid
     * @param hisName
     * @return
     */
    public static InfoBlogFragment newInstance(int hisUid, String hisName) {
        InfoBlogFragment ff = new InfoBlogFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("hisUid", hisUid);
        bundle.putString("hisName", hisName);
        ff.setArguments(bundle);
        BLOG_FLAG = 2;

        return ff;
    }

    private String getArgsType() {
        return getArguments().getString("type");
    }

    private int getArgsUserId() {
        return getArguments().getInt("hisUid");
    }

    private String getArgsUserName() {
        return getArguments().getString("hisName");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        appContext = (AppContext) getActivity().getApplication();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_ptr_list, container, false);
        mPullRefreshListView = (ListView) view.findViewById(R.id.pull_refresh_list);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mPullRefreshListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Blog blog = null;
                // 判断是否是TextView
                if (view instanceof TextView) {
                    blog = (Blog) view.getTag();
                } else {
                    TextView tv = (TextView) view.findViewById(R.id.blog_listitem_title);
                    blog = (Blog) tv.getTag();
                }
                if (blog == null) {
                    return;
                }
                // 跳转到博客详情
                UIHelper.showUrlRedirect(view.getContext(), blog.getUrl());
            }
        });

        mNewsAdapter = new ListViewBlogAdapter(getActivity(), BlogList.CATALOG_LATEST, lvNewsDataList, R.layout.blog_listitem);
        mPullRefreshListView.setAdapter(mNewsAdapter);

        // TODO 第一次启动时候加载数据
        new GetFansTask().execute();

    }

    /**
     * 加载数据AsyncTask
     */
    private class GetFansTask extends AsyncTask<Void, Void, BlogList> {

        @Override
        protected BlogList doInBackground(Void... params) {
            // 当前pageIndex
            int pageIndex = lvSumData / 20;
            String type = getArgsType();
            if (BLOG_FLAG == 1) {
                try {
                    return appContext.getBlogList(type, pageIndex, true);
                } catch (AppException e) {
                    e.printStackTrace();
                }

            } else if (BLOG_FLAG == 2) {
                try {
                    return appContext.getUserBlogList(getArgsUserId(), getArgsUserName(), pageIndex, true);
                } catch (AppException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(BlogList result) {
            super.onPostExecute(result);

            if (result != null) {
                List<Blog> blogList = result.getBloglist();
                // 加载成功且如果有数据
                if (blogList != null && blogList.size() > 0) {
                    // 如果是用户中心的博客，则给博客Tab设置博客数量
                    if (BLOG_FLAG == 2) {
                        ((MainActivity)getActivity()).getSupportActionBar().getTabAt(2).setText(getString(R.string.blog_with_count, result.getBlogsCount()));
                    }
                    lvSumData += blogList.size();
                    lvNewsDataList.addAll(result.getBloglist());
                    mNewsAdapter.notifyDataSetChanged();
                }
                // 加载失败或者没有数据
                else {
                    Toast.makeText(getActivity(), "加载失败或者没有博客", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

}
